/**
 * 
 */
package com.google.code.log4j.appenders;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

/**
 * @author nmukhtar
 *
 */
public class SpeechAppender extends AppenderSkeleton {
	private String voiceName = "kevin16";
	private Voice loggerVoice;
	
	/**
	 * @return the voiceName
	 */
	public String getVoiceName() {
		return voiceName;
	}

	/**
	 * @param voiceName the voiceName to set
	 */
	public void setVoiceName(String voiceName) {
		this.voiceName = voiceName;
	}

	/* (non-Javadoc)
	 * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
	 */
	@Override
	protected void append(LoggingEvent event) {
		if (event != null) {
			if (loggerVoice != null) {
				if (layout != null) {
					loggerVoice.speak(layout.format(event));
					if (layout.ignoresThrowable()) {
			            String[] s = event.getThrowableStrRep();
			            if (s != null) {
			                StringBuilder buf = new StringBuilder();
			                for(int i = 0; i < s.length; i++) {
			                    buf.append(s[i]);
			                    buf.append("\r\n");
			                }
			                loggerVoice.speak(buf.toString());
			            }
					}
				} else {
					loggerVoice.speak(event.getMessage().toString());
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.apache.log4j.Appender#close()
	 */
	@Override
	public void close() {
		loggerVoice.deallocate();
	}

	/* (non-Javadoc)
	 * @see org.apache.log4j.Appender#requiresLayout()
	 */
	@Override
	public boolean requiresLayout() {
		return true;
	}
	
	@Override
	public void activateOptions() {
		super.activateOptions();
        VoiceManager voiceManager = VoiceManager.getInstance();
        loggerVoice = voiceManager.getVoice(voiceName);

        if (loggerVoice == null) {
        	LogLog.error("Cannot find a voice named "
                    + voiceName + ".  Please specify a different voice.");
        }
        
        /* Allocates the resources for the voice.
         */
        loggerVoice.allocate();
	}
}
